"""
通知相关异步任务
用于发送邮件、Webhook、钉钉/企业微信通知等
"""
from celery_app import celery_app
from typing import Dict, Any


@celery_app.task(name="tasks.notification.send_email")
def send_email_notification(
    to: str,
    subject: str,
    body: str,
    html: bool = False
) -> Dict[str, Any]:
    """
    发送邮件通知
    
    Args:
        to: 收件人
        subject: 主题
        body: 内容
        html: 是否为HTML格式
    
    Returns:
        dict: 发送结果
    """
    try:
        # 实现邮件发送逻辑
        # import smtplib
        # from email.mime.text import MIMEText
        # ...
        
        print(f"[EMAIL] To: {to}, Subject: {subject}")
        
        return {
            'status': 'success',
            'to': to,
            'message': '邮件发送成功'
        }
    except Exception as e:
        return {
            'status': 'failed',
            'error': str(e)
        }


@celery_app.task(name="tasks.notification.send_webhook")
def send_webhook_notification(
    url: str,
    data: Dict[str, Any],
    headers: Dict[str, str] = None
) -> Dict[str, Any]:
    """
    发送 Webhook 通知
    
    Args:
        url: Webhook URL
        data: 数据
        headers: 请求头
    
    Returns:
        dict: 发送结果
    """
    try:
        import requests
        
        response = requests.post(
            url,
            json=data,
            headers=headers or {},
            timeout=10
        )
        
        return {
            'status': 'success',
            'status_code': response.status_code,
            'response': response.text[:200]  # 只保留前200字符
        }
    except Exception as e:
        return {
            'status': 'failed',
            'error': str(e)
        }


@celery_app.task(name="tasks.notification.send_dingtalk")
def send_dingtalk_notification(
    webhook_url: str,
    message: str,
    at_mobiles: list = None
) -> Dict[str, Any]:
    """
    发送钉钉通知
    
    Args:
        webhook_url: 钉钉机器人 Webhook URL
        message: 消息内容
        at_mobiles: @的手机号列表
    
    Returns:
        dict: 发送结果
    """
    try:
        import requests
        
        data = {
            "msgtype": "text",
            "text": {
                "content": message
            },
            "at": {
                "atMobiles": at_mobiles or [],
                "isAtAll": False
            }
        }
        
        response = requests.post(
            webhook_url,
            json=data,
            timeout=10
        )
        
        return {
            'status': 'success',
            'response': response.json()
        }
    except Exception as e:
        return {
            'status': 'failed',
            'error': str(e)
        }

